/**
 * Created by Alice on 2016/9/22 0022
 */

//排期ID
var uid = utils.get_url_param("planUid");
//法庭ID
// var cid = utils.get_url_param("cid");

// var third = utils.get_url_param("third");
// var now_video = utils.get_url_param('vc');
var record_casename = null;
var record_caseno = null;
$(function () {

    if (navigator.appName.indexOf("Microsoft Internet") == -1) {
        onVLCPluginReady()
    }
    else if (document.readyState == 'complete') {
        onVLCPluginReady();
    }
    else {
        /* Explorer loads plugins asynchronously */
        document.onreadystatechange = function () {
            if (document.readyState == 'complete') {
                onVLCPluginReady();
            }
        }
    }
    // if ('null' == uid) {
    //     $("#title").html('&nbsp;暂无案件信息');
    // } else {
    //     getCaseInfoByIdForToday(uid);
    // }
    // var currentServerIp = currentServerIP();
    // if (third) {
    //     getThirdcfg(cid, currentServerIp);
    // } else {
    //     getCgf(uid, cid, currentServerIp, now_video);
    // }

    // if (third) {
    //     getThirdcfg(cid, currentServerIp);
    // } else {

    // }

    $("#_nav_court_info").click(function () {
        $("#_nav_court_p").attr("class", "");
        $("#_nav_court_info").attr("class", "active");
        $("#_court_case").hide();
        $("#_court_info").show();
    });
    $("#loading").hide();

});


function getCaseInfoByIdForToday(result) {
    // $.ajax({
    //     url: r.base_path + "getCaseInfoByUid",
    //     type: "post",
    //     dataType: "json",
    //     data: {
    //         uid: uid,
    //         courtId: now_video
    //     },
    //     success: function (result) {
    // console.log(result)
    var caseInfo = result;
    var archives = caseInfo.archives;
    var caseName = caseInfo.caseName;
    //记录案件名称、案号，并向后台发送点播信息
    record_caseno = archives;
    record_casename = caseName;
    playRecordinfo();
    var caseTypeName = caseInfo.casetypeName;
    var judge_user_uid = caseInfo.judgeUserUid;
    var secretary_uid = caseInfo.secretaryUserUid;
    var courtroomName = caseInfo.courtRoomName;
    var statusName = caseInfo.statusName;
    var parties = caseInfo.accuse + " " + caseInfo.accused;
    var startDate = caseInfo.startDate;
    // startDate = startDate.substring(0, startDate.length - 2);
    var planDate = caseInfo.planDate;
    // planDate = planDate.substring(0, planDate.length - 2);
    var caseDesc = caseInfo.detail;
    if (caseDesc == null) {
        caseDesc = "";
    }
    // console.log(result);
    var title_text = '&nbsp;' + archives + '——' + caseName;
    if (title_text.length > 50) {
        title_text = title_text.substring(0, 50) + '...';
        // console.log(title_text)
    }
    $("#title").html(title_text);
    var html = ['  <div class="">',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span> 案  号：</span>',
        '                            </div>',
        '                            <div class="col-md-9 col-xs-8 text-left">',
        '                                <span>' + archives + '</span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>案件类型：</span>',
        '                            </div>',
        '                            <div class="col-md-3 col-xs-8 text-left">',
        '                                <span>' + caseTypeName + '</span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>案件名称：</span>',
        '                            </div>',
        '                            <div class="col-md-9 col-xs-8 text-left">',
        '                                <span>' + caseName + '</span>',
        '                            </div>',
        '                        </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <a href="javascript:n.chat(\'' + 'megumin' + '\')"><span> <i class="fa fa-wechat"></i>审判长：</span></a>',
        '                            </div>',
        '                            <div class="col-md-3  col-xs-8 text-left">',
        '                                <span><a id="judge_name" href="' + r.base_path + "more/more_review?judge=" + judge_user_uid + "&city=" + vlcCourtUid + "&court=" + r.court_uid + '" class="white-a cursor-hand">' + (caseInfo.judgeName ? caseInfo.judgeName : '') + '</a></span>',
        '                            </div>',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                            </div>',
        '                            <div class="col-md-3  col-xs-8 text-left">',
        '                            </div>',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <a href="javascript:n.chat(\'' + 'aly' + '\')"><span> <i class="fa fa-wechat"></i>书记员：</span></a>',
        '                            </div>',
        '                            <div class="col-md-3  col-xs-8 text-left">',
        '                                <span><a id="secretary_name" href="' + r.base_path + "more/more_review?secretary=" + secretary_uid + "&city=" + vlcCourtUid + "&court=" + r.court_uid + '" class="white-a cursor-hand">' + ( caseInfo.secretaryName ? caseInfo.secretaryName : '') + '</a></span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>当事人：</span>',
        '                            </div>',
        '                            <div class="col-md-9 col-xs-8 text-left">',
        '                                <span>' + parties + '</span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span> 开庭地点：</span>',
        '                            </div>',
        '                            <div class="col-md-9 col-xs-8 text-left">',
        '                                <span>' + (courtroomName ? courtroomName : '') + '</span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>排期时间：</span>',
        '                            </div>',
        '                            <div class="col-md-9 col-xs-8 text-left">',
        '                                <span>' + planDate + '</span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>开庭时间：</span>',
        '                            </div>',
        '                            <div class="col-md-9 col-xs-8 text-left">',
        '                                <span>' + startDate + '</span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span> 庭审状态:</span>',
        '                            </div>',
        '                            <div class="col-md-3 col-xs-8 text-left">',
        '                                <span>' + statusName + '</span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>   基本案情：</span>',
        '                            </div>',
        '                            <div class="col-md-9 col-xs-8 text-left">',
        '                                <span>' + caseDesc + '</span>',
        '                            </div>',
        '                        </div>',
        '                    </div>'].join("");
    $("#_court_info").html(html);
    $("#_court_info").show();
    // },
    // error: function () {
    // }
    // });
}

// function currentServerIP() {
//     var ip = '';
//     $.ajax({
//         url: r.base_path + "getCourtIpByCourtId",
//         type: 'post',
//         data:{
//         	courtId:now_video
//         },
//         async: false,
//         dataType: "json",
//         success: function (result) {
//             ip = result.data;
//         }
//     });
//     return ip;
// }

// function getThirdcfg(cid, courtIp) {
//     var channel = utils.get_url_param("channel");
//     if (!channel) {
//         channel = 1;
//     }
//     $(".nav-live").empty();
//     $.post(r.base_path + "sys/courtSetting/selectThirdCfg", {cId: cid, courtId: now_video}, function (result) {
//         if (result && result.status == 0) {
//             var data = result.data;
//             var count = 0;
//             $(".nav-live").empty();
//             for (var key in  data) {
//                 $(".nav-live").append('<li role="presentation"><a href="javascript:void(0);">' + key + '</a></li>');
//                 count = count + 1;
//             }
//             $(".nav-live").find("li").eq(channel - 1).attr("class", "active");
//             var d = $(".nav-live").find("li").eq(channel - 1).find("a").html();
//             // console.log(data,d);
//             var cha = data[d];//默认显示
//             initialise(courtIp, cha);
//             $(".nav-live").find("li").click(function () {
//                 var inx = $(".nav-live").find("li").index(this) + 1;
//                 window.location.href = "living.html?uid=" + uid + "&cid=" + cid + "&channel=" + inx + "&vc=" + now_video;
//             });
//         }
//     })
// }

function getCfg(planUid, courtRoomUid, currentServerIp, vlcCourtUid, channel) {
    var channel = utils.get_url_param("channel");
    if (!channel) {
        channel = 1;
    }
    $(".nav-live").empty();
    $.ajax({
        url: r.base_path + "courtRoom/getCfgInfo",
        type: "post",
        dataType: "json",
        data: {
            courtRoomUid: courtRoomUid,
            // channelFlag: channel,
            serverIp: currentServerIp
        },
        success: function (result) {
            // console.log(result)
            if (result != null) {
                var data = result.data;
                var count = 0;
                $(".nav-live").empty();
                for (var key in  data) {
                    $(".nav-live").append('<li role="presentation"><a href="javascript:void(0);">' + key + '</a></li>');
                    count = count + 1;
                }
                $(".nav-live").find("li").eq(channel - 1).attr("class", "active");
                var d = $(".nav-live").find("li").eq(channel - 1).find("a").html();
                var cha = data[d];//默认显示
                initialise(currentServerIp, cha);
                $(".nav-live").find("li").click(function () {
                    var inx = $(".nav-live").find("li").index(this) + 1;
                    window.location.href = r.base_path + "system_monitor/panel_living?planUid=" + planUid + "&courtRoomUid=" + courtRoomUid + "&vlcCourtUid=" + vlcCourtUid + "&channel=" + inx;
                });
            }
        },
        error: function () {
        }
    });
}
function initialise(courtIp, cfg) {
    // console.info(courtIp, cfg);
    var vlc = getVLC("vlc");
    if (vlc) {
        vlc.playlist.items.clear();
        while (vlc.playlist.items.count > 0) {
            // clear() may return before the playlist has actually been cleared
            // just wait for it to finish its job
        }
        var options = [":rtsp-tcp"];
        var itemId;
        // if (third) {
        //     console.log(cfg);
        //     itemId = vlc.playlist.add(cfg, "", options);
        // } else {
        console.log("rtsp://" + courtIp + "/" + cfg);
        itemId = vlc.playlist.add("rtsp://" + courtIp + "/" + cfg, "", options);
        // }
        if (itemId != -1) {
            vlc.playlist.playItem(itemId);
        }
        else {
            alert("cannot play at the moment !");
        }
    }
}


function getVLC(name) {
    if (window.document[name]) {
        return window.document[name];
    }
    if (navigator.appName.indexOf("Microsoft Internet") == -1) {
        if (document.embeds && document.embeds[name])
            return document.embeds[name];
    }
    else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
    {
        return document.getElementById(name);
    }
}

// VLC Plugin
function onVLCPluginReady() {
    registerVLCEvent("MediaPlayerMediaChanged", handleMediaPlayerMediaChanged);
    registerVLCEvent("MediaPlayerNothingSpecial", handle_MediaPlayerNothingSpecial);
    registerVLCEvent("MediaPlayerOpening", handle_MediaPlayerOpening);
    registerVLCEvent("MediaPlayerBuffering", handle_MediaPlayerBuffering);
    registerVLCEvent("MediaPlayerPlaying", handle_MediaPlayerPlaying);
    registerVLCEvent("MediaPlayerPaused", handle_MediaPlayerPaused);
    registerVLCEvent("MediaPlayerStopped", handle_MediaPlayerStopped);
    registerVLCEvent("MediaPlayerForward", handle_MediaPlayerForward);
    registerVLCEvent("MediaPlayerBackward", handle_MediaPlayerBackward);
    registerVLCEvent("MediaPlayerEndReached", handle_MediaPlayerEndReached);
    registerVLCEvent("MediaPlayerEncounteredError", handle_MediaPlayerEncounteredError);
    registerVLCEvent("MediaPlayerTimeChanged", handle_MediaPlayerTimeChanged);
    registerVLCEvent("MediaPlayerPositionChanged", handle_MediaPlayerPositionChanged);
    registerVLCEvent("MediaPlayerSeekableChanged", handle_MediaPlayerSeekableChanged);
    registerVLCEvent("MediaPlayerPausableChanged", handle_MediaPlayerPausableChanged);
    registerVLCEvent("MediaPlayerTitleChanged", handle_MediaPlayerTitleChanged);
    registerVLCEvent("MediaPlayerLengthChanged", handle_MediaPlayerLengthChanged);
}

function close() {
}

function registerVLCEvent(event, handler) {
    var vlc = getVLC("vlc");

    if (vlc) {
        if (vlc.attachEvent) {
            // Microsoft
            vlc.attachEvent(event, handler);
        } else if (vlc.addEventListener) {
            // Mozilla: DOM level 2
            vlc.addEventListener(event, handler, true);
        } else {
            // DOM level 0
            eval("vlc.on" + event + " = handler");
        }
    }
}

// JS VLC API callbacks
function handleMediaPlayerMediaChanged() {
    // document.getElementById("info").innerHTML = "Media Changed";
}

function handle_MediaPlayerNothingSpecial() {
    // document.getElementById("state").innerHTML = "Idle...";
}

function handle_MediaPlayerOpening() {
    // onOpen();
}

function handle_MediaPlayerBuffering(val) {
    // document.getElementById("info").innerHTML = val + "%";
}

function handle_MediaPlayerPlaying() {
    // onPlay();
}

function handle_MediaPlayerPaused() {
    // onPause();
}

function handle_MediaPlayerStopped() {
    // onStop();
}

function handle_MediaPlayerForward() {
    // document.getElementById("state").innerHTML = "Forward...";
}

function handle_MediaPlayerBackward() {
    // document.getElementById("state").innerHTML = "Backward...";
}

function handle_MediaPlayerEndReached() {
    // onEnd();
}

function handle_MediaPlayerEncounteredError() {
    // onError();
}

function handle_MediaPlayerTimeChanged(time) {
    var vlc = getVLC("vlc");
    if (vlc) {
        var mediaLen = vlc.input.length;
        if (mediaLen > 0) {
            // seekable media
            // info.innerHTML = formatTime(time) + "/" + formatTime(mediaLen);
        }
    }
}

function handle_MediaPlayerPositionChanged(val) {
    // set javascript slider to correct position
}

function handle_MediaPlayerSeekableChanged(val) {
    // setSeekable(val);
}

function handle_MediaPlayerPausableChanged(val) {
    // setPauseable(val);
}

function handle_MediaPlayerTitleChanged(val) {
    //setTitle(val);
    document.getElementById("info").innerHTML = "Title: " + val;
}

function handle_MediaPlayerLengthChanged(val) {
    //setMediaLength(val);
}

function onPlaying() {
    var vlc = getVLC("vlc");
    if (vlc) {
        var mediaLen = vlc.input.length;
        if (mediaLen > 0) {
            //获取当前播放视频的时长
            // console.log(formatTime(mediaLen));
        }
    }
}

function unregisterVLCEvent(event, handler) {
    var vlc = getVLC("vlc");

    if (vlc) {
        if (vlc.detachEvent) {
            // Microsoft
            vlc.detachEvent(event, handler);
        } else if (vlc.removeEventListener) {
            // Mozilla: DOM level 2
            vlc.removeEventListener(event, handler, true);
        } else {
            // DOM level 0
            eval("vlc.on" + event + " = null");
        }
    }
}

//定时记录点播人员记录
function playRecordinfo() {
    var userName = $.cookie('_username');
    var courtUid = $.cookie('_court_uid');
    console.info(userName, courtUid, record_caseno, record_casename, planUid);
    var data = {
        userName: userName,
        courtUid: courtUid,
        planUid: planUid,
        caseNo: record_caseno,
        caseName: record_casename,
        type: "1"
    };
    data = JSON.stringify(data);

    var webSocket =
        new WebSocket('ws://localhost:8080/cmp/recordPlayList');

    webSocket.onerror = function (event) {
        console.info(event);
    };

    webSocket.onopen = function (event) {
        webSocket.send(data);
    };

    webSocket.onmessage = function (event) {
        console.info(event);
    };

    window.onbeforeunload = function () {
        webSocket.close();
    };

}

